# coding=utf8

import sys
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header
import httplib
import BaseHTTPServer


class SystemInfo:
    def ShowInfo(self):
        print("platform : " + sys.platform)
        print("api_version : %d" % sys.api_version)
        print("builtin_module_names : ")
        for m in sys.builtin_module_names:
            print("    " + m)


def CreateFile(filename, content):
    fp = open(filename, 'w')
    if fp:
        fp.write(content)
        fp.close()


def ReadFile(filename):
    fp = open(filename, 'r')
    if fp:
        s = fp.read()
        fp.close()
        return s
    return None


class MailSender:
    def __init__(self, host, port, user, password):
        self.host = host
        self.port = port
        self.user = user
        self.password = password
        self.message = MIMEMultipart()
        self.message["From"] = Header(self.user)
        self.lastError = ""

    def sendMail(self, receiver, subject, content):

        self.message["To"] = Header(receiver)
        self.message["Subject"] = Header(subject, "utf-8")
        self.message.attach(MIMEText(content, 'plain', 'utf-8'))

        try:
            server = smtplib.SMTP(self.host, self.port)
            server.login(self.user, self.password)
            server.sendmail(self.user, receiver, self.message.as_string())
            server.close()
            return True
        except smtplib.SMTPAuthenticationError:
            self.lastError = "Authentication Error"
            return False
        except smtplib.SMTPConnectError:
            self.lastError = "Connect Error"
            return False
        except smtplib.SMTPDataError:
            self.lastError = "Data Error"
            return False
        except smtplib.SMTPRecipientsRefused:
            self.lastError = "Recipients Refused"
            return False
        except smtplib.SMTPException:
            self.lastError = "Unknow Error"
            return False

# class HTTPServer (BaseHTTPServer.BaseHTTPRequestHandler):
#     def __init__(self,host,port):
#         self.server=BaseHTTPServer.BaseHTTPRequestHandler()

# def createHttpServer(server_class=BaseHTTPServer,handler_class=BaseHTTPServer.BaseHTTPRequestHandler):
#     server_address=('',8888)
#     handler_class=BaseHTTPServer.BaseHTTPRequestHandler()
#     httpd=server_class(server_address,handler_class)
#     httpd.server_forever()


class HTTPClient:

    exceptionAddress=["127.0.0.1","localhost"]

    def __init__(self, proxy_host=None, proxy_port=8080, timeout=5):
        self.proxy_host = proxy_host
        self.proxy_port = proxy_port
        self.timeout = timeout

    def isLocalAddress(self, url):
        for s in self.exceptionAddress:
            if url.find(s)!=-1 :
                return True

    def get(self, url):
        try:
            
            if self.proxy_host and not self.isLocalAddress(url) :
                host=self.proxy_host
                port=self.proxy_port
                path=url
            else:
                if url.startswith("http://"):
                    url = url[7:]
                start_idx=url.find("/")
                # 查找path
                if start_idx == -1:
                    path = "/"
                    host=url
                else:
                    path = url[start_idx:]
                    host = url[:start_idx]
                start_idx=url.find(":")
                # 查找端口
                if start_idx != -1 :
                    port = int(host[start_idx + 1:])
                    host = host[:start_idx]
                else:
                    port = 80
            
            client = httplib.HTTPConnection(host, port)
            client.timeout = self.timeout
            client.request("GET", path)
            res = client.getresponse()
            self.status=res.status
            self.reason=res.reason
            self.lastError=""
            ret=res.read()
            client.close()
            return ret
        except httplib.HTTPException as e:
            self.lastError = e.message

 
    def post(self, url,params):
        try:            
            if self.proxy_host and not self.isLocalAddress(url) :
                host=self.proxy_host
                port=self.proxy_port
                path=url
            else:
                if url.startswith("http://"):
                    url = url[7:]
                start_idx=url.find("/")
                # 查找path
                if start_idx == -1:
                    path = "/"
                    host=url
                else:
                    path = url[start_idx:]
                    host = url[:start_idx]
                start_idx=url.find(":")
                # 查找端口
                if start_idx != -1 :
                    port = int(host[start_idx + 1:])
                    host = host[:start_idx]
                else:
                    port = 80
            client = httplib.HTTPConnection(host, port)
            client.timeout = self.timeout

            headers = {"Content-type": "application/x-www-form-urlencoded",
                "Accept": "text/plain"}

            client.request("POST", path, params, headers)
            res = client.getresponse()
            self.status=res.status
            self.reason=res.reason
            self.lastError=""
            ret=res.read()
            client.close()
            return ret
        except httplib.HTTPException as e:
            self.lastError = e.message